package com.example.microservicediscoveryeureka.controller;

import com.example.microservicecommon.User;
import com.example.microservicediscoveryeureka.service.UserService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
public class MovieController {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    @HystrixCommand(fallbackMethod = "findAllFallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "10000")
    },threadPoolProperties = {
            @HystrixProperty(name = "coreSize",value = "1"),
            @HystrixProperty(name = "maxQueueSize",value = "10")
    })
    public Object findAll(){
        return restTemplate.getForObject("http://microservice-provider-user/users",Object.class);
    }

    public Object findAllFallback(){
        return new User("失败默认用户","222");
    }

    @GetMapping("/user/{id}")
    public Object findbyid(@PathVariable String id){
        return userService.findById(id);
    }

    @GetMapping("/choose")
    public Object choose(){
        return loadBalancerClient.choose("microservice-provider-user");
    }

    @GetMapping("/showInfo")
    public Object showInfo(){
        return discoveryClient.getInstances("microservice-provider-user");
    }
}
